
var reconnectTimes = 0 // 重连次数
var reconnectTimesMax = 0
var reconnectInterval = 1000 * 40 // 重连间隔5秒
// var url = "ws://"+ process.env.VUE_APP_BASE_API.split('//')[1] +"/ws/test"
var url =  process.env.VUE_APP_WEBSOCKET_URL

let ws = null

export function initWebSocket() {
  ws = new WebSocket(url);

  ws.onopen = () => {
    // console.log('WebSocket连接成功');
  };

  ws.onerror = () => {
    // console.log('WebSocket连接发生错误');
    reconnect();
  };

  ws.onclose = () => {
    // console.log('WebSocket连接已关闭');
    reconnect();
  };
  ws.onmessage = function (event) {
    // console.log('收到WebSocket消息: ', JSON.parse(event.data).orderId);
    localStorage.setItem('WebSocket', JSON.parse(event.data).orderId)
  };
  // 其他的ws事件处理...
}

function reconnect() {
  if (reconnectTimesMax === 0 ? true : reconnectTimes < reconnectTimesMax) { // 最多重连5次
    setTimeout(() => {
      reconnectTimes++;
      initWebSocket();
    }, reconnectInterval);
  } else {
    console.error('重连次数达到上限，不再尝试重连');
  }
}


export function beforeDestroys() {
  if (ws) {
    ws.close(); // 在组件销毁前关闭WebSocket连接
  }
}

// export  {initWebSocket,beforeDestroy};
